//
//  ViewController.m
//  Dispatch
//
//  Created by hyeyeon on 14. 1. 13..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "ViewController.h"
#define INTROIMAGE_TAG      100 //인트로 애니메이션>이미지들태그
#define MENUVIEW_TAG        200 //메뉴뷰 태그
#define STARVIEW_TAG        300 //스타정보리스트뷰 태그
#define SEARCHVIEW_TAG      400 //검색뷰 태그
#define BATTLINGVIEW_TAG    500 //무한배틀 태그
#define BATTLERANKING_TAG   600 //배틀랭킹 태그

@interface ViewController ()

@end

@implementation ViewController
@synthesize titleView, responseData, introView, finishedAnimation;
@synthesize issueView, rankingView, myView, battleView;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    //facebook login
//    FBLoginView *loginview = [[FBLoginView alloc] init];
    
    appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    self.responseData = [NSMutableData data];
    
    [appDelegate analyticsScreen];
    [self maketitleView];   //타이틀 생성
    
    //리스트뷰
    menuBackView = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                            titleView.frame.origin.y+titleView.frame.size.height,
                                                            mySize.width,
                                                            mySize.height-titleView.frame.size.height-20)];
    menuBackView.backgroundColor = ColorFromRGB(0x413c43);
    [self.view addSubview:menuBackView];

    
    
    
    //sdk생성
    if (languagesKorean) {
        [self makeManBanner];
    }else{
        [self makeIadBanner];
    }
    //인트로 애니메이션 호출
    [self introLogoAnimation];
    
    self.view.backgroundColor = ColorFromRGB(0xe9e9e9);

    
//    [self sdkHidden:YES];
   
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (manBanner) {
        [manBanner viewShowState:YES];
    }
    
    if (selectViewIndex != 4) {
            [self requestSDK];
    }

    
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (manBanner) {
        [manBanner viewShowState:NO];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 인트로 애니메이션

-(void)introLogoAnimation{
    
    introBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mySize.width, mySize.height)];
    introBackView.backgroundColor = ColorFromRGB(0xf2f2f2);
    [self.view addSubview:introBackView];
    
    
    UIImageView *introImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, mySize.width, mySize.height)];
    introImage.backgroundColor = ColorFromRGB(0xf2f2f2);
    introImage.image = [UIImage imageNamed:[self getImageName:@"intro_mezzo"]];
    [self.view addSubview:introImage];
    [self logoAnimationComplete:introImage];
}


-(void)logoAnimationComplete:(UIImageView*)logoView{
    
    
    [UIView animateWithDuration:0.5f animations:^{
        logoView.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [logoView removeFromSuperview];
        [self initIntroAnimationImages];
        [introBackView removeFromSuperview];
    }];
    
}

-(void)initIntroAnimationImages{
    
    
    introView = [[UIView alloc] initWithFrame:CGRectMake(0, myOrginY, mySize.width, mySize.height-myOrginY)];
    introView.backgroundColor = ColorFromRGB(0xf2f2f2);
    [self.view addSubview:introView];
    
    NSArray *mixArray = [[NSArray alloc] initWithArray:[self arrayRandomNumber]];
    
    for (int index = 0; index<12; index++) {
        NSString *imageName = [self getImageName:[NSString stringWithFormat:@"intro_%02d",index+1]];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
        imageView.image = [UIImage imageNamed:imageName];
        imageView.tag = INTROIMAGE_TAG+index;
        
        //좌표
        NSInteger coordinate = [[mixArray objectAtIndex:index] integerValue];
        NSInteger x = coordinate%3;
        NSInteger y = coordinate/3;
        
        float originX = x*(introView.frame.size.width/3.0f);
        float originY = (float)y*(introView.frame.size.height/4.0f);
        
        imageView.frame = CGRectMake(originX, originY, introView.frame.size.width/3.0f, introView.frame.size.height/4.0f);
        
        imageView.alpha = 0.0f;
        
        
        [introView addSubview:imageView];
        
        
    }
    
    
    [self introAnimationStart];
}

//섞기
-(NSArray*)arrayRandomNumber{
    
    srand(time(0));
    NSMutableArray *numberArray = [NSMutableArray arrayWithObjects:
                                   [NSNumber numberWithInteger:0],
                                   [NSNumber numberWithInteger:1],
                                   [NSNumber numberWithInteger:2],
                                   [NSNumber numberWithInteger:3],
                                   [NSNumber numberWithInteger:4],
                                   [NSNumber numberWithInteger:5],
                                   [NSNumber numberWithInteger:6],
                                   [NSNumber numberWithInteger:7],
                                   [NSNumber numberWithInteger:8],
                                   [NSNumber numberWithInteger:9],
                                   [NSNumber numberWithInteger:10],
                                   [NSNumber numberWithInteger:11], nil];
    
    for (int i = 0; i<[numberArray count]-1; i++) {
        int r = rand()%[numberArray count];
        [numberArray exchangeObjectAtIndex:r withObjectAtIndex:i];
        
    }
    
    return (NSArray*)numberArray;
}

-(void)introAnimationStart{
    
    NSArray *numberArray = [[NSArray alloc] initWithArray:[self arrayRandomNumber]];
    
    //섞은 순서대로 아이콘 나타나게 하기
    for (int index = 0; index<[numberArray count]; index++) {
        NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:[numberArray objectAtIndex:index],@"index", nil];
        if (index < [numberArray count]-1) {
            
            [NSTimer scheduledTimerWithTimeInterval:0.15*index
                                             target:self
                                           selector:@selector(appearIntroIcon:)
                                           userInfo:userInfo
                                            repeats:NO];
        }else{
            
            [NSTimer scheduledTimerWithTimeInterval:0.15*index
                                             target:self
                                           selector:@selector(appearLastIntroIcon:)
                                           userInfo:userInfo
                                            repeats:NO];
        }
    }
}

-(void)appearIntroIcon:(NSTimer*)timer{
    NSInteger index = [[timer.userInfo objectForKey:@"index"] integerValue]+INTROIMAGE_TAG;
    UIImageView *imageView = (UIImageView*)[introView viewWithTag:index];
    
    [UIView animateWithDuration:0.3f animations:^{
        imageView.alpha = 1.0f;
    }];
    
    //    UIView *moveview = (UIView *)[timer userInfo];
}

-(void)appearLastIntroIcon:(NSTimer*)timer{
    
    NSInteger index = [[timer.userInfo objectForKey:@"index"] integerValue]+INTROIMAGE_TAG;
    UIImageView *imageView = (UIImageView*)[introView viewWithTag:index];
    
    [UIView animateWithDuration:0.3f animations:^{
        imageView.alpha = 1.0f;
    } completion:^(BOOL finished) {
        [self introAnimationComplete];
    }];
}

-(void)introAnimationComplete{
    
    UIImageView *introLogoImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, mySize.width, mySize.height)];
    introLogoImage.image = [UIImage imageNamed:[self getImageName:@"intro_bg"]];
    [introView addSubview:introLogoImage];
    introLogoImage.alpha = 0.0f;
    
    
    [UIView animateWithDuration:0.5f animations:^{
        introLogoImage.alpha = 1.0f;
    } completion:^(BOOL finished) {
        
//        [self startInitLoad];
        self.finishedAnimation = YES;
        
        if (![appDelegate connectedToNetwork]) {
            [self introAnimationEnd];
            return ;
        }

        if (issueView) {
            if (issueView.finishLoad) {
                
                [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(introAnimationEnd) userInfo:nil repeats:NO];
            }
        }
        
    }];
}

-(void)introAnimationEnd{
    
    [UIView animateWithDuration:0.5f animations:^{
        introView.alpha = 0.0f;
    } completion:^(BOOL finished) {
        
        if (introView) {
            
            if ([introView subviews]) {
                [introView removeFromSuperview];
                introView = nil;
            }
        }
        
        [self sdkHidden:NO];
        
        
    }];
    

}

-(NSString*)getImageName:(NSString*)name
{
    return deviceIphone4 ? name : [NSString stringWithFormat:@"%@@5",name];
}

#pragma mark - 타이틀
-(void)maketitleView{
    titleView = [[TitleView alloc] initWithFrame:CGRectMake(0, myOrginY, mySize.width, 106)];
    titleView.delegate = self;
    [self.view addSubview:titleView];
    titleView.backgroundColor = ColorFromRGB(0xe9e9e9);
}

#pragma mark 타이틀의 메뉴버튼 클릭
-(void)clickMenu:(NSInteger)menuIndex{
    //menuIndex -> 1:이슈, 2:배틀, 3:직찍, 4:마이, 5:랭킹, 6:검색
    
    CGRect rect = CGRectMake(0, 0, menuBackView.frame.size.width, menuBackView.frame.size.height);

    if (menuIndex == 1) {
        if (!issueView) {
            issueView = [[IssueView alloc] initWithFrame:rect];
            [menuBackView addSubview:issueView];
        }
        issueView.frame = rect;
        issueView.tag = MENUVIEW_TAG+menuIndex;
        [issueView drawRect:rect];
        [menuBackView bringSubviewToFront:issueView];
    }else if(menuIndex == 2){
        if (!battleView) {
            battleView = [[BattleView alloc] initWithFrame:rect];
            [menuBackView addSubview:battleView];
        }
        battleView.tag = MENUVIEW_TAG+menuIndex;
        battleView.frame = rect;
        [menuBackView bringSubviewToFront:battleView];
    }else if(menuIndex == 3){
        if (!captureView) {
            captureView = [[CaptureView alloc] initWithFrame:rect];
            [menuBackView addSubview:captureView];
        }
        captureView.frame = rect;
        captureView.tag = MENUVIEW_TAG+menuIndex;
        [menuBackView bringSubviewToFront:captureView];
    }else if(menuIndex == 4){

        if (!myView) {
            myView = [[MyView alloc] initWithFrame:rect];
            [menuBackView addSubview:myView];
        }else{
            //기존에 생성되어있고 다시 들어가면 자료들 리로드 시켜줌..
            if (myView.followButton.selected) {
                [myView requestFollowList];
            }else if (myView.issueButton.selected){
                [myView requestInterestIssueWithPage:1];
            }else if (myView.settingButton.selected){
                [myView requestCheckNotice];
            }
        }
        myView.frame = rect;
        myView.tag = MENUVIEW_TAG+menuIndex;
        [menuBackView bringSubviewToFront:myView];

    }else if(menuIndex == 5){
        if (!rankingView) {
            rankingView = [[RankingView alloc] initWithFrame:rect];
            [menuBackView addSubview:rankingView];
        }
        rankingView.frame = rect;
        rankingView.tag = MENUVIEW_TAG+menuIndex;
        [menuBackView bringSubviewToFront:rankingView];
    }else if (menuIndex == 6){
        searchUnderView = selectViewIndex;
        [self appearSearchView];
    }
    
    //타이틀뷰 샛팅
    [titleView selectMenuButton:menuIndex];
    
    //화면전환시 appear와 disappear호출
    
    
    if (selectViewIndex == menuIndex) {
        NSLog(@"같은화면부름");
    }else{
        
        
        if (selectViewIndex > 0) {
            [self selectViewDisappear:selectViewIndex]; //기존 화면
        }
        [self selectViewAppear:menuIndex];  //이번에 나오는 화면
    }
    
    selectViewIndex = menuIndex;
    
}

#pragma mark 랭킹 롤링시작
-(void)startRankingRolling{
    [titleView startRankingRolling];
}


#pragma mark - 네트워크

-(void)requestPhotoID:(NSString*)photoID{
    
    
    NSString *dataStr = [NSString stringWithFormat:@"id=%@&lang=%@&deviceid=%@",photoID,appDelegate.currentLanguage,[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"]];
    dataStr = [appDelegate encryptDataURLString:dataStr];
//    NSString *requesturl  =[NSString stringWithFormat:@"%@?id=%@&lang=%@",URL_PHOTO,photoID,appDelegate.currentLanguage];
    NSString *requesturl  =[NSString stringWithFormat:@"%@?p=%@",URL_PHOTO,dataStr];
    [self requestURL:requesturl];
}

-(void)requestURL:(NSString*)url{
    
    [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        duringNetwork = YES;
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            if(connection){
                NSLog(@"이슈리스트 네트워크 요청 : %@",url);
            }
            
        }
    }
}

#pragma mark delegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio{
    
    duringNetwork = NO;
    
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];

    //dispatch://launch?pid=?로 들어왔을때
    if ([resultDictionary objectForKey:@"return_code"]) {
        if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
            
            NSLog(@"resultDictionary : %@",resultDictionary);
            [self apearPhotoViewContollerWithPhotoDIC:resultDictionary];
            
        }
    }
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    duringNetwork = NO;
}


#pragma mark - SDK
#pragma mark MAN
-(void)makeManBanner{
    float origin = deviceIOS7 ? mySize.height-48 : mySize.height-48-20;
    manBanner = [[ADBanner alloc] initWithFrame:CGRectMake(0, origin, mySize.width, 48)];
    [manBanner applicationID:@"dispatch/dispatch/" adWindowID:@"banner"];
    manBanner.delegate = self;
    [manBanner startBannerAd];
    [self.view addSubview:manBanner];
}

-(void)requestManSDK{
    NSLog(@"인터넷 재요청");
    //sdk재요청
    if (manBanner) {
        [manBanner startBannerAd];
    }else{
        [self makeManBanner];
    }
}

//delegate
- (void)didReceiveAd:(ADBanner*)adBanner chargedAdType:(BOOL)bChargedAdType{
    
    NSLog(@"맨 광고 완료");
    currentSDKIndex = 1;
    
    NSLog(@"self.childViewControllers : %d",[self.childViewControllers count]);
}

- (void)didFailReceiveAd:(ADBanner*)adBanner errorType:(NSInteger)errorType{
    
    NSLog(@"맨 광고 에러 : %d",errorType);
    currentSDKIndex = 0;
}


#pragma mark admob
-(void)makeAdmobBanner{
    
    float origin = deviceIOS7 ? mySize.height-50 : mySize.height-50-20;
    if (!admobBanner) {
        
        admobBanner = [[GADBannerView alloc] initWithFrame:CGRectMake(0, origin, mySize.width, 50)];
    }
    admobBanner.delegate = self;
    admobBanner.rootViewController = self;
    admobBanner.adUnitID = @"a1515d24e50d0c0";
    if (![admobBanner superview]) {
        [self.view addSubview:admobBanner];
    }
    [admobBanner loadRequest:[GADRequest request]];
    
    admobBanner.hidden = YES;

    
}


-(void)stopAdmob{
    if ([admobBanner superview]) {
        [admobBanner removeFromSuperview];
    }
}


//딜리게이트
-(void)adViewDidReceiveAd:(GADBannerView *)view{
    
    NSLog(@"애드몹 광고 완료");
    if (iadBanner) {
        iadBanner.hidden = YES;
    }
    currentSDKIndex = 3;
    
    if (!iadBanner.hidden) {
        admobBanner.hidden = YES;
        
    }else if(!introView){
        admobBanner.hidden = NO;
    }else if (![introView superview]){
        admobBanner.hidden = NO;
    }
    
}

-(void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error{
    
    NSLog(@"애드몹 광고 에러 : %@",error);
    currentSDKIndex = 0;
    
}

#pragma mark iad
-(void)makeIadBanner{
    
    float origin = deviceIOS7 ? mySize.height-50 : mySize.height-50-20;
    if ([ADBannerView instancesRespondToSelector:@selector(initWithAdType:)]) {
        iadBanner = [[ADBannerView alloc] initWithAdType:ADAdTypeBanner];
    }else{
        iadBanner = [[ADBannerView alloc] init];
    }
    iadBanner.backgroundColor = [UIColor clearColor];
    iadBanner.delegate = self;
    iadBanner.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifierPortrait];
    iadBanner.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
    iadBanner.frame = CGRectMake(0, origin, 320, 50);

    [self.view addSubview:iadBanner];
    
}

//delegate
-(BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave{
    return YES;
}

-(void)bannerViewDidLoadAd:(ADBannerView *)banner{
    NSLog(@"아이애드 광고완료");
    iadBanner.hidden = NO;
    
    if (admobBanner) {
        [self stopAdmob];
    }
    currentSDKIndex = 2;
}

-(void)bannerViewActionDidFinish:(ADBannerView *)banner{
    
}

-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error{
    NSLog(@"아이애드 에러 : %@",error);
    
    [self makeAdmobBanner];
    
    if (iadBanner) {
        iadBanner.hidden = YES;
    }
}

#pragma mark sdk 숨김
-(void)sdkHidden:(BOOL)yn{
    
    if (currentSDKIndex == 1) {
//        manBanner.hidden = yn;
        [self effectShow:yn andTargetView:manBanner];
        
    }else if(currentSDKIndex == 2){
        //        iadBanner.hidden = yn;
        [self effectShow:yn andTargetView:iadBanner];
    }else if(currentSDKIndex == 3){
        if (admobBanner) {
            if ([admobBanner superview]) {
                //                admobBanner.hidden = yn;
                [self effectShow:yn andTargetView:admobBanner];
            }
        }
    }
    
}

-(void)effectShow:(BOOL)yn andTargetView:(UIView*)tView{
    
    float gap = deviceIOS7 ? 0 : myOrginY;
    if (yn) {
        
        tView.frame = CGRectMake(0, mySize.height-gap-tView.frame.size.height, tView.frame.size.width, tView.frame.size.height);
        [UIView animateWithDuration:0.3f animations:^{
            tView.frame = CGRectMake(0, mySize.height, tView.frame.size.width, tView.frame.size.height);
        } completion:^(BOOL finished) {
            
        }];
    }else{
        tView.frame = CGRectMake(0, mySize.height, mySize.width, tView.frame.size.height);
        [UIView animateWithDuration:0.3f animations:^{
            tView.frame = CGRectMake(0, mySize.height-gap-tView.frame.size.height, tView.frame.size.width, tView.frame.size.height);
        } completion:^(BOOL finished) {
        }];
    }
    
}




-(void)putSDKFront{
    if (currentSDKIndex == 1) {
        [self.view bringSubviewToFront:manBanner];
    }else if(currentSDKIndex == 2){
        
        [self.view bringSubviewToFront:iadBanner];
    }else if(currentSDKIndex == 3){
        if (admobBanner) {
            [self.view bringSubviewToFront:admobBanner];
        }
    }
}

#pragma mark 재요청
-(void)requestSDK{
    if (languagesKorean) {
        [self requestManSDK];
    }else{
        if (iadBanner.hidden) {
            
            [admobBanner loadRequest:[GADRequest request]];
        }else{
            
        }
    }
}

#pragma mark - 메일
-(void)appearMail{
    
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
        mailController.mailComposeDelegate = self;
        [mailController setToRecipients:[NSArray arrayWithObjects:@"sp@mezzomedia.co.kr", nil]];
        [mailController setSubject:NSLocalizedString(@"DisPatchMail", @"[Dispatch] KOREAN STAR PHOTO NEWS HD")];
        
        [self presentModalViewController:mailController animated:YES];
    }else{
        //메일을 보낼수 없음
        [appDelegate alertViewWithMessage:NSLocalizedString(@"emailAccount", @"") andTimeInterval:2.0];
    }
}

#pragma mark delegate

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
	//	message.hidden = NO;
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
			//			message.text = @"Result: canceled";
			break;
		case MFMailComposeResultSaved:
			//			message.text = @"Result: saved";
			break;
		case MFMailComposeResultSent:
            [appDelegate alertViewWithMessage:@"sent Mail" andTimeInterval:2.0];
			//			message.text = @"Result: sent";
			break;
		case MFMailComposeResultFailed:
			//			message.text = @"Result: failed";
			break;
		default:
			//			message.text = @"Result: not sent";
			break;
	}
    [controller dismissViewControllerAnimated:YES completion:nil];
    
    
	//[issuController dismissModalViewControllerAnimated:YES];
}

#pragma mark - 메뉴뷰 컨트롤
//appear, disappear

-(void)selectViewAppear:(NSInteger)index{
    //menuIndex -> 1:이슈, 2:배틀, 3:직찍, 4:마이, 5:랭킹, 6:검색

    if (index == 1) {
        [self requestSDK];
        [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_ISSUE Label:ANA_LAB_Issue_List];
    }else if(index == 2){
        
        [self requestSDK];
        [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_BATTLE Label:ANA_LAB_Battle_Home];
    }else if(index == 3){
        
        [self requestSDK];
    }else if(index == 4){
        [myView appearView];
        [self sdkHidden:YES];
    }else if(index == 5){
        
        [self requestSDK];
    }else if(index == 6){
        
        [self requestSDK];
        [appDelegate analyticsCategory:ANA_CAT_CLICK Action:ANA_ACT_SEARCH Label:ANA_LAB_C_Search];
        
    }
}

-(void)selectViewDisappear:(NSInteger)index{
    
    //menuIndex -> 1:이슈, 2:배틀, 3:직찍, 4:마이, 5:랭킹, 6:검색
    if (index == 1) {
    }else if(index == 2){
        
    }else if(index == 3){
        
    }else if(index == 4){
        
        [self sdkHidden:NO];
    }else if(index == 5){
        
    }else if(index == 6){
        
    }
}

#pragma mark - 페이스북

//-(void)facebookWithURL:(NSString*)urlStr andTitle:(NSString*)title andCaption:(NSString*)caption{
//    
//}
//
//- (void)performPublishAction:(void(^)(void))action {
//    // we defer request for permission to post to the moment of post, then we check for the permission
//    if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound) {
//        // if we don't already have the permission, then we request it now
//        [FBSession.activeSession requestNewPublishPermissions:@[@"publish_actions"]
//                                              defaultAudience:FBSessionDefaultAudienceFriends
//                                            completionHandler:^(FBSession *session, NSError *error) {
//                                                if (!error) {
//                                                    action();
//                                                } else if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
//                                                }
//                                            }];
//    } else {
//        action();
//    }
//    
//}
//
////로그인
//-(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView{
//    
//}
//
//-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user{
//    
//}
//
//- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView{
//    
//    //맨첨으로 들어옴
//    FBShareDialogParams *p = [[FBShareDialogParams alloc] init];
//    p.link = [NSURL URLWithString:@"http://developers.facebook.com/ios"];
//#ifdef DEBUG
//    [FBSettings enableBetaFeatures:FBBetaFeaturesShareDialog];
//#endif
//    BOOL canShareFB = [FBDialogs canPresentShareDialogWithParams:p];
//    BOOL canShareiOS6 = [FBDialogs canPresentOSIntegratedShareDialogWithSession:nil];
//    
//    enableFacebook = canShareFB || canShareiOS6;
//}
//
//- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error{
//    
//}
//
//-(BOOL)facebookIsOpen{
//    return [FBSession.activeSession isOpen];
//}
//
//
//- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
//    
//    NSArray *permissions = [[NSArray alloc] initWithObjects:
//                            @"publish_stream",
//                            nil];
//    
//    return [FBSession openActiveSessionWithPublishPermissions:permissions
//                                              defaultAudience:FBSessionDefaultAudienceFriends
//                                                 allowLoginUI:allowLoginUI
//                                            completionHandler:^(FBSession *session, FBSessionState state, NSError *error)   {
//                                                
//                                                [self sessionStateChanged:session
//                                                                    state:state
//                                                                    error:error];
//                                            }];
//}
//
//- (void)sessionStateChanged:(FBSession *)session
//                      state:(FBSessionState) state
//                      error:(NSError *)error
//{
//    switch (state) {
//        case FBSessionStateOpen:
//            if (!error) {
//                NSLog(@"FBSessionStateOpen");
//            }
//            break;
//        case FBSessionStateClosed:
//        case FBSessionStateClosedLoginFailed:
//            break;
//        default:
//            break;
//    }
//    
//    [[NSNotificationCenter defaultCenter]
//     postNotificationName:FBSessionStateChangedNotification
//     object:session];
//    
//    if (error) {
//        UIAlertView *alertView = [[UIAlertView alloc]
//                                  initWithTitle:@"Error"
//                                  message:error.localizedDescription
//                                  delegate:nil
//                                  cancelButtonTitle:@"OK"
//                                  otherButtonTitles:nil];
//        [alertView show];
//    }
//    
//}


#pragma mark - 검색
-(void)appearSearchView{
    
    SearchView *searchView = [[SearchView alloc] initWithFrame:CGRectMake(mySize.width, myOrginY, mySize.width, mySize.height-20)];
    searchView.tag = SEARCHVIEW_TAG;
    [self.view addSubview:searchView];
    [self putSDKFront];
    
    [UIView animateWithDuration:0.5f animations:^{
        searchView.frame = CGRectMake(0, myOrginY, mySize.width, mySize.height-20);
    }];
}

-(void)removeSearchView{
    
    SearchView *searchView = (SearchView*)[self.view viewWithTag:SEARCHVIEW_TAG];
    if ([searchView superview]) {
        [UIView animateWithDuration:0.5f animations:^{
            searchView.frame  = CGRectMake(mySize.width, myOrginY, mySize.width, mySize.height-20);
        } completion:^(BOOL finished) {
            
            [searchView removeFromSuperview];
        }];
    }
    
    //보여지는뷰 인덱스 샛팅
    NSLog(@"select under view : %d",searchUnderView);
    [self selectViewDisappear:6];//서치뷰인덱스
    [self selectViewAppear:searchUnderView];
    selectViewIndex = searchUnderView;
}

#pragma mark - 스타
-(void)appearStarListToID:(NSString*)starID{

    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_STAR Label:ANA_LAB_Star_Home];
    StarView *starView = [[StarView alloc] initWithFrame:CGRectMake(mySize.width, myOrginY, mySize.width, mySize.height-20)];
    starView.tag = STARVIEW_TAG;
    starView.starID = starID;
    [self.view addSubview:starView];
    [starView requestStarInfoList];
    [self putSDKFront];
    
    [UIView animateWithDuration:0.5f animations:^{
        starView.frame = CGRectMake(0, myOrginY, mySize.width, mySize.height-20);
    }];
    
}

-(void)appearStarListToID:(NSString *)starID andPushID:(NSString*)pushID{
    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_STAR Label:ANA_LAB_Star_Home];
    StarView *starView = [[StarView alloc] initWithFrame:CGRectMake(mySize.width, myOrginY, mySize.width, mySize.height-20)];
    starView.tag = STARVIEW_TAG;
    starView.starID = starID;
    [self.view addSubview:starView];
    [starView requestStarInfoListWithPushID:pushID];
    [self putSDKFront];
    
    [UIView animateWithDuration:0.5f animations:^{
        starView.frame = CGRectMake(0, myOrginY, mySize.width, mySize.height-20);
    }];
}

-(void)removeStarView{
    
    
    StarView *starView = (StarView*)[self.view viewWithTag:STARVIEW_TAG];
    if ([starView superview]) {
        [UIView animateWithDuration:0.5f animations:^{
            starView.frame  = CGRectMake(mySize.width, myOrginY, mySize.width, mySize.height-20);
        } completion:^(BOOL finished) {
            
            [starView removeFromSuperview];
        }];
    }
}


#pragma mark - 무한배틀
-(void)appearBattlingView:(NSNumber*)number{
    
    BattlingView *battlingView = [[BattlingView alloc] initWithFrame:CGRectMake(mySize.width, myOrginY, mySize.width, mySize.height-20)];
    battlingView.firstIndex = [number integerValue];
    battlingView.tag = BATTLINGVIEW_TAG;
    [self.view addSubview:battlingView];
    [self putSDKFront];
    
    [UIView animateWithDuration:0.5f animations:^{
        battlingView.frame = CGRectMake(0, myOrginY, mySize.width, mySize.height-20);
    }completion:^(BOOL finished) {
        [battlingView didAppear];
    }];
}

-(void)removeBattlingView{
    
    BattlingView *battlingView = (BattlingView*)[self.view viewWithTag:BATTLINGVIEW_TAG];
    if ([battlingView superview]) {
        [UIView animateWithDuration:0.5f animations:^{
            battlingView.frame  = CGRectMake(mySize.width, myOrginY, mySize.width, mySize.height-20);
        } completion:^(BOOL finished) {
            
            [battlingView removeFromSuperview];
        }];
    }
}

#pragma mark - 배틀지난순위보기
-(void)appearBattleRankingViewWithDate:(NSString*)dateStr{
    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_BATTLE Label:ANA_LAB_Battle_Lastlist];
    
    BattleRankingView *bRankingView = [[BattleRankingView alloc] initWithFrame:CGRectMake(mySize.width, myOrginY, mySize.width, mySize.height-20)];
    bRankingView.dateString = dateStr;
    bRankingView.tag = BATTLERANKING_TAG;
    [bRankingView requestDate:dateStr andPage:1];
    [self.view addSubview:bRankingView];
    [self putSDKFront];
    
    
    [UIView animateWithDuration:0.5f animations:^{
        bRankingView.frame = CGRectMake(0, myOrginY, mySize.width, mySize.height-20);
    }];
}


-(void)removeBattleRankingView{
    
    BattleRankingView *bRankingView = (BattleRankingView*)[self.view viewWithTag:BATTLERANKING_TAG];
    if ([bRankingView superview]) {
        [UIView animateWithDuration:0.5f animations:^{
            bRankingView.frame  = CGRectMake(mySize.width, myOrginY, mySize.width, mySize.height-20);
        } completion:^(BOOL finished) {
            
            [bRankingView removeFromSuperview];
        }];
    }
}

#pragma mark - PhotoViewController
-(void)apearPhotoViewContollerWithPhotoDIC:(NSDictionary*)photoDIC{
    
    PhotoViewController *photoController = [[PhotoViewController alloc] init];
    photoController.parentClassIndex = 3;
    photoController.mDelegate = self;
    [photoController setIssueIndex:0];
    [photoController setOnePhotoImage:photoDIC];
    [self presentModalViewController:photoController animated:YES];
    
}



//스키마를 통해 들어옴
-(void)apearPhotoControllerFromScheme:(NSInteger)menuIndex andId:(NSString*)idStr{
    if (menuIndex == 1) {
        //이슈
        [issueView appearPhotoViewControllerWithID:idStr];
    }
}


@end
